package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInstFunc;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class SafeQryEparchyByProvinceAttrHandler extends AbstractAttrHandler<KiteInst, AttrData> {
    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Override
    public void after(KiteAttr attr, KiteInst inst, AttrData data) {
        super.after(attr, inst, data);
        if(KiteStringUtils.equals(attr.getFieldName(),"210004150")){
            List<AttrValue> attrValues = new ArrayList<>();
            String custId = data.getCustId();
            KiteProdInstFunc prodInstFunc = querySceneInstService.getProdInstFunc(custId, inst.getInstId());
            if(Objects.nonNull(prodInstFunc)){
                List<KiteProdInstFunc> prodFuncInstList = querySceneInstService.listProdInstFuncsByProdId(custId, prodInstFunc.getAccProdInstId(), "20210326017");
                if(KiteListUtils.isNotEmpty(prodFuncInstList)){
                    attrValues = AttrValueCache.get(attr.getAttrId());
                    if(KiteListUtils.isNotEmpty(attrValues)){
                        Set<String> attrSet = prodFuncInstList.stream().map(funcInst -> funcInst.getAttrValue("210004150")).collect(Collectors.toSet());
                        attrValues.removeIf(attrValue -> !attrSet.contains(attrValue.getAttrValue()));
                    }
                }
            }
            attr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValues, KiteAttrValue.class));
            if(KiteListUtils.isEmpty(attrValues)){
                attr.setValue("");
                attr.setValueDesc("");
                attr.setDefaultValue("");
            }else {
                attr.setValue(attrValues.get(0).getAttrValue());
                attr.setValueDesc(attrValues.get(0).getAttrValueDesc());
            }
        }
    }
}
